package com.cn.aam.checaiduo.ui.useraccess;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cn.aam.checaiduo.BuildConfig;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListener;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.base.web.NormalWebActivity;
import com.cn.aam.checaiduo.bean.UserB;
import com.cn.aam.checaiduo.bean.base.BaseResponseB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.center.CustomDialogCenter;
import com.cn.aam.checaiduo.center.SharePreferenceCenter;
import com.cn.aam.checaiduo.center.UserCenter;
import com.cn.aam.checaiduo.utils.AuthUtil;
import com.cn.aam.checaiduo.utils.MyEditTextUtils;
import com.cn.aam.checaiduo.utils.StringUtil;
import com.cn.aam.checaiduo.widget.WMToast;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 注册操作
 */
public class RegisterActivity extends BaseActivity {


    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.et_invite_code)
    EditText etInviteCode;//邀请码

    @BindView(R.id.tv_send_code)
    TextView tvSendCode;

    @BindView(R.id.tv_tip)
    TextView tvTip;//提示


    private CountDownTimer cd;


    private boolean getCodeIng = false;//正在获取验证码中

    private String mobile;
    private String code;
    private String pwd;

    private String invite_code;//邀请码

    public static Intent newInstance(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        return intent;
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_register;
    }


    @Override
    protected void initView() {
        initTvTips();
        initToolBar();
    }

    protected void initToolBar() {
        ToolBarManager.with(this, WMContent)
                .setBackgroundColor(R.color.color_transparent)
                .setTitle("注册")
                .setNavigationIcon(R.drawable.ic_nav_arrow_white);
    }

    private void initTvTips() {
        SpannableString span = new SpannableString(getString(R.string.tip_register_protocol));


        span.setSpan(new ForegroundColorSpan(Color.parseColor("#FEC760")), 2, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//染色
        span.setSpan(new clickSpan(), 15, 21, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//点击事件
        tvTip.setText(span);
        tvTip.setMovementMethod(LinkMovementMethod.getInstance());//必须设置才能点击
    }

    private class clickSpan extends ClickableSpan {

        @Override
        public void onClick(View widget) {
            //服务协议
            String protocol = RetrofitHome.HOST_API + "wap/Usercenter/registerAgreement.html";
            startActivity(NormalWebActivity.newInstance(mContext, protocol, "悟空车注册协议"));
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(Color.parseColor("#FEC760"));
            ds.setUnderlineText(false);
        }


    }

    /**
     * 获取所有的数值
     */
    private void getAllValue() {
        mobile = MyEditTextUtils.getContent(etAccount);
        code = MyEditTextUtils.getContent(etCode);
        pwd = MyEditTextUtils.getContent(etPwd);
        invite_code = MyEditTextUtils.getContent(etInviteCode);
    }

    //发送验证码
    @OnClick(R.id.tv_send_code)
    public void onSendCode() {
        if (checkMobileValue())
            doSendCode();
    }

    //注册
    @OnClick(R.id.btn_register)
    public void onRegister() {
        if (checkAllValue())
            doRegisterStep1();
    }

    private void doSendCode() {
        RetrofitHome.getInstance()
                .getUserApi()
                .getMsgCode(mobile)
                .compose(RxSchedulers.<BaseResponseB>toMain())
                .subscribe(new OnRequestListener<BaseResponseB>(this) {

                    @Override
                    public void onNext(BaseResponseB value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_SUCCESS)
                            startCountTime();
                    }
                });
    }

    /**
     * 检测手机号码
     *
     * @return 通过为 true 不同过为false
     * @info 此处可以无限增加各种检查条件
     */
    private boolean checkMobileValue() {
        getAllValue();
        if (TextUtils.isEmpty(mobile)) {
            WMToast.normal("请输入手机号码");
            return false;
        }
        if (!AuthUtil.isMobileNo(mobile)) {
            WMToast.normal("请输入正确的手机号码");
            return false;
        }
        return true;
    }


    /**
     * 检测所有值
     *
     * @return 通过为 true 不同过为false
     * @info 此处可以无限增加各种检查条件
     */
    private boolean checkAllValue() {
        getAllValue();
        if (!getCodeIng) {
            WMToast.normal("请获取验证码");
            return false;
        }
        if (!checkMobileValue())
            return false;
        if (TextUtils.isEmpty(mobile)) {
            WMToast.normal("请输入用户名");
            return false;
        }
        if (TextUtils.isEmpty(code)) {
            WMToast.normal("请输入验证码");
            return false;
        }
        if (TextUtils.isEmpty(pwd)) {
            WMToast.normal("请输入密码");
            return false;
        }
        if (!StringUtil.isValidateWith(pwd)) {
            WMToast.normal("请确保密码是6~16位字母与数字的组成");
            return false;
        }
        return true;
    }

    /**
     * 开始注册 步骤1
     */
    private void doRegisterStep1() {
        RetrofitHome.getInstance()
                .getUserApi()
                .registerStep1(mobile, code)
                .compose(RxSchedulers.<BaseResponseB>toMain())
                .subscribe(new OnRequestListener<BaseResponseB>(this) {
                    @Override
                    protected String getProgressBarContent() {
                        return "校验中...";
                    }

                    @Override
                    public void onNext(BaseResponseB value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_SUCCESS)
                            doRegisterStep2();
                    }
                });

    }

    /**
     * 开始注册 步骤2
     */
    private void doRegisterStep2() {

        RetrofitHome.getInstance()
                .getUserApi()
                .registerStep2(mobile, pwd, invite_code, BuildConfig.code)
                .compose(RxSchedulers.<BaseResponseB>toMain())
                .subscribe(new OnRequestListener<BaseResponseB>(this) {

                    @Override
                    protected String getProgressBarContent() {
                        return "注册中...";
                    }

                    @Override
                    public void onNext(BaseResponseB value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_SUCCESS)
                            doLogin();
                    }
                });

    }


    /**
     * 开始登录
     */
    private void doLogin() {
        RetrofitHome.getInstance()
                .getUserApi()
                .login(mobile, pwd)
                .compose(RxSchedulers.<NormalResponseB<UserB>>toMain())
                .subscribe(new OnRequestV2Listener<UserB>(this) {

                    @Override
                    protected String getProgressBarContent() {
                        return "登录中...";
                    }

                    @Override
                    public void onNext(NormalResponseB<UserB> value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_FAILED) {
                            return;
                        }
                        //save mobile
                        SharePreferenceCenter.getInstance().savePhone(MyEditTextUtils.getContent(etAccount));

                        //save user data
                        UserCenter.getInstance().setUser(value.getData());

                        //go to registerSuccess page
                        startActivity(RegisterSuccessResultActivity.newInstance(mContext));
                        endThisPage();
                    }
                });
    }


    /**
     * 开始倒计时
     */
    private void startCountTime() {
        WMToast.normal("验证码已发送");
        getCodeIng = true;
        tvSendCode.setEnabled(false);
        //倒计时60s
        cd = new CountDownTimer(Const.MSG_COUNT_DOWN * 1000, 1000) {
            @Override
            public void onTick(long l) {
                tvSendCode.setText("重新发送(" + l / 1000 + "s)");
            }

            @Override
            public void onFinish() {
                endCountTime();
            }
        };
        cd.start();
    }

    /**
     * 结束倒计时
     */
    private void endCountTime() {
        if (cd != null) {
            cd.cancel();
            cd = null;
        }
        getCodeIng = false;
        tvSendCode.setText("获取验证码");
        tvSendCode.setEnabled(true);
    }

    @Override
    public void onBackPressed() {
        CustomDialogCenter
                .getInstance()
                .showExitRegisterDialog(mContext, new CustomDialogCenter.CallBack() {
                    @Override
                    public void onCall() {
                        endThisPage();
                    }
                });
    }


    private void endThisPage() {
        endCountTime();
        finish();
    }
}
